package cn.edu.gdut.csq.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class SystemScript {

	// 执行爬虫
	public static void startSpider(String spidercmd) {

		try {
			Process proc = Runtime.getRuntime().exec(
					"cmd /c D: && cd D:\\python\\workspace\\work\\jobspider\\ "
							+ spidercmd);
			System.out.println(proc);
			BufferedReader in = new BufferedReader(new InputStreamReader(
					proc.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				System.out.println(line);
			}
			in.close();
			// Thread.sleep(1000 * 60 * 3);
			proc.waitFor();

		} catch (Exception e) {
			System.out.println("Error!");
		}
	}

	public static Object exec(String cmd) {
		try {
			String[] cmdA = { "/bin/sh", "-c",
					"cd /home/chesian/workspaces/jobspider/ " + cmd };
			Process process = Runtime.getRuntime().exec(cmdA);
			LineNumberReader br = new LineNumberReader(new InputStreamReader(
					process.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
				sb.append(line).append("\n");
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void excuteCMD() {

		Runtime runtime = Runtime.getRuntime();
		try {
			runtime.exec("cmd \\k start python D:\\Programs\\workspace\\chesian\\week13\\aibin.py");
			System.out.println("sss");

		} catch (Exception e) {
			System.out.println("Error!");
		}
	}
	
	public static Object testExec(String cmd) {
		try {
			String[] cmdA = { "/bin/sh", "-c",
					"cd /home/chesian/workspaces/jobspider/ " + cmd };
			Process process = Runtime.getRuntime().exec(cmdA);
			LineNumberReader br = new LineNumberReader(new InputStreamReader(
					process.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
				sb.append(line).append("\n");
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		String spidernames[] = { "job51Spider", "job58Spider", "zhaopinSpider" };
		String spidercmd = "";
		for (int i = 0; i < spidernames.length; i++) {
			spidercmd += " && python startup.py " + spidernames[i];
		}
		// System.out.println(spidercmd);
		// SystemScript.startSpider(spidercmd);

		SystemScript.exec(spidercmd);

		// SystemScript.excuteCMD();
	}
}
